const vscode = require("vscode");
const request = require("request");
var DKData = require("./data.js");

function DK(response, my_jar, headers) {
    return new Promise((resolve) => {
        if (response.body.search("hasFlag: '1'") != -1) {
            vscode.window.showInformationMessage('今日已打卡，不需要再次打卡');
            resolve();
        } else {
            // 今天还没打卡
            if (response.body.match(/getdqtlqk/g).length != 15 ||
            response.body.match(/</g).length != 1251 ||
            response.body.match(/active/g).length != 72) {
                vscode.window.showErrorMessage("表单已修改，请自行填报或通知开发者");
                
                resolve();
            }
            var data = DKData.configure;
            var area = vscode.workspace.getConfiguration("zjuhealthreport").get("area");
            var province = area.split(" ")[0];
            var city = area.split(" ")[1];
            var id = response.body.match(/"id":"?(\d*)"?,/g)[0];
            var uid = response.body.match(/"uid":"?(\d*)"?,/g)[0];
            var date = response.body.match(/"date":"?(\d*)"?,/g)[0];
            var created = response.body.match(/"created":"?(\d*)"?,/g)[0];
            // 修改数据
            data["area"] = area;
            data["province"] = province;
            data["city"] = city;
            data["uid"] = uid;
            data["id"] = id;
            data["date"] = date;
            data['created'] = created;

            
            // 填报数据
            var data2 = {
                'error': '{"type":"error","message":"Get geolocation time out.Get ipLocation failed.","info":"FAILED","status":0}'
            }
            // progress.report({ increment: 40, message: "正在发送打卡数据" });
            vscode.window.showInformationMessage("正在发送打卡数据");
            setTimeout(() => {
                request({
                    url: 'https://healthreport.zju.edu.cn/ncov/wap/default/save-geo-error',
                    method: 'POST',
                    headers: headers,
                    jar: my_jar,
                    form: data2
                }, (error, response) => {
                    setTimeout(() => {
                        request({
                            url: 'https://healthreport.zju.edu.cn/ncov/wap/default/save',
                            method: 'POST',
                            headers: headers,
                            jar: my_jar,
                            form: data
                        }, (error, response) => {
                            if (response.body.search('"e":0') != -1) {
                                vscode.window.showInformationMessage("打卡成功");
                            } else {
                                vscode.window.showErrorMessage("打卡失败");
                            }
                            resolve();
                        })
                    }, 3000)
                })
            }, 3000)
        }
    })
}

exports.DK = DK;